package com.collaborativelearning;

import com.collaborativelearning.dummy.Management;
import com.collaborativelearning.dummy.User;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class LoginActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);

		TextView registerScreen = (TextView) findViewById(R.id.link_to_register);
		// Listening to register new account link
		registerScreen.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// Switching to Register screen
				Intent i = new Intent(getApplicationContext(),
						RegisterActivity.class);
				startActivity(i);
			}
		});

		final EditText login_email = (EditText) findViewById(R.id.login_email);
		final EditText login_password = (EditText) findViewById(R.id.login_password);
		Button btnLogin = (Button) findViewById(R.id.btnLogin);
		btnLogin.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {

				// delete errors from prev. click!
				login_email.setError(null);
				login_password.setError(null);
				boolean found = false;
				boolean match = false;

				for (User user : Management.INSTANCE.getUsers()) {
					if (login_email.getText().toString().trim()
							.equals(user.getEmail())) {
						found = true;
						if (login_password.getText().toString().trim()
								.equals(user.getPassword())) {
							match = true;
							break;
						}
					}
				}

				if (!found) {
					login_email.setError("بريدك غير صحيح!");
					return;
				}
				if (!match) {
					login_password
							.setError("كلمة السر غير صحيحة!");
					return;
				}

				if (login_email.getText().toString().trim()
						.equalsIgnoreCase("ahmed@gmail.com")) {
					Management.INSTANCE.setStudent(true);
					Management.INSTANCE.setTeacher(false);
					Intent i = new Intent(getApplicationContext(),
							StudentHomePage.class);
					startActivity(i);
				} else {
					if (login_email.getText().toString().trim()
							.equalsIgnoreCase("mohamed@gmail.com")) {
						Management.INSTANCE.setTeacher(true);
						Management.INSTANCE.setStudent(false);
						Intent i = new Intent(getApplicationContext(),
								TeacherHomePage.class);
						startActivity(i);
					}
				}
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_login, menu);
		return true;
	}

}
